package com.ict.txmsv2.controllerAdvice;

import cn.hutool.json.JSONUtil;
import com.ict.txmsv2.model.*;
import com.ict.txmsv2.services.RecordService;
import com.ict.txmsv2.utils.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author yoleen
 * @date 2020/3/28 14:39
 */

@Aspect
@Component
@Order(1)
public class LogAspect {
    public final static Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Autowired
    RecordService recordService;

    @Pointcut("execution(* com.ict.txmsv2.controller..*.*(..))")
    public void pointcut() {
    }

    @Before(value = "pointcut()")
    public void doBefore(JoinPoint jp) {
//        String name = jp.getSignature().getName();
//        System.out.println(name + "方法开始执行。。");
    }

    @After(value = "pointcut()")
    public void doAfter(JoinPoint jp) {
//        String name = jp.getSignature().getName();
//        System.out.println(name + "方法执行结束。。");
    }

    @AfterReturning(value = "pointcut()", returning = "result")
    public void doAfterReturning(JoinPoint jp, Object result) {
//        String name = jp.getSignature().getName();
//        System.out.println(name+"方法返回值为："+JSONUtil.parse(result));
//        logger.info("{}", JSONUtil.parse(result));
    }

    @Around(value = "pointcut()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        Signature signature = pjp.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        long startTime = System.currentTimeMillis();
        Object result = pjp.proceed();
        WebLog webLog = new WebLog();
        long endTime = System.currentTimeMillis();
        webLog.setSpendTime((int)(endTime-startTime));
        if (method.isAnnotationPresent(MethodDescrition.class)) {
            MethodDescrition methodDescrition = method.getAnnotation(MethodDescrition.class);
            webLog.setDescription(methodDescrition.value());
        }
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return result;
        }
        HttpServletRequest request = attributes.getRequest();
        webLog.setIP(getIpAdrress(request));
        webLog.setMethod(request.getMethod());
        webLog.setParameters(getParameter(method,pjp.getArgs()));
        webLog.setUri(request.getRequestURI());
        webLog.setUrl(request.getRequestURL().toString());
        if (!"GET".equals(webLog.getMethod())){
            Record record = new Record();
            record.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            User currentHr = UserUtils.getCurrentHr();
            if(currentHr ==null){
                record.setUserid(1);
            }
            else {
                record.setUserid(currentHr.getId());
            }
            record.setBrief(webLog.getDescription());
            String content = JSONUtil.toJsonStr(webLog);
            if (content.length()<1024)
            {
                record.setInfo(content);
            }
            recordService.addRecord(record);
        }
        webLog.setResult(result);
        logger.info("{}",JSONUtil.parse(webLog));
        return result;
    }

    /**
     * 获取Ip地址
     *
     * @param request
     * @return
     */
    private String getIpAdrress(HttpServletRequest request) {
        String Xip = request.getHeader("X-Real-IP");
        String XFor = request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = XFor.indexOf(",");
            if (index != -1) {
                return XFor.substring(0, index);
            } else {
                return XFor;
            }
        }
        XFor = Xip;
        if (StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)) {
            return XFor;
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getRemoteAddr();
        }
        return XFor;
    }


    /**
     * 根据方法和传入的参数获取请求参数
     * @param method
     * @param args
     * @return
     */
    private Object getParameter(Method method, Object[] args) {
        List<Object> argList = new ArrayList<>();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            //将RequestBody注解修饰的参数作为请求参数
            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
            if (requestBody != null) {
                if (args[i] instanceof FaceSearch){
                    FaceSearch faceSearch = (FaceSearch) args[i];
                    faceSearch.setFile(null);
                    argList.add(faceSearch);
                }
                else if (args[i] instanceof RegisterFace){
                    RegisterFace registerFace = (RegisterFace) args[i];
                    registerFace.setFile(null);
                    argList.add(registerFace);
                }
                else {
                    argList.add(args[i]);
                }
            }
            //将RequestParam注解修饰的参数作为请求参数
            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
            if (requestParam != null) {
                Map<String, Object> map = new HashMap<>();
                String key = parameters[i].getName();
                if (!StringUtils.isEmpty(requestParam.value())) {
                    key = requestParam.value();
                }
                map.put(key, args[i]);
                argList.add(map);
            }
        }
        if (argList.size() == 0) {
            return null;
        } else if (argList.size() == 1) {
            return argList.get(0);
        } else {
            return argList;
        }
    }
}

